#!/usr/bin/env pwsh

# GRUB2引导加载程序构建脚本
# 支持BIOS和UEFI双启动模式

# 设置变量
$BOOT_DIR = "$PSScriptRoot"
$GRUB_DIR = "$BOOT_DIR/grub"
$EFI_DIR = "$BOOT_DIR/efi/boot"
$CONFIG_DIR = "$GRUB_DIR/grub.d"
$OUTPUT_DIR = "$BOOT_DIR/output"

function Check-Command {
    param($cmd)
    try { Get-Command $cmd -ErrorAction Stop > $null
        return $true
    } catch { return $false }
}

function Print-Header {
    Write-Host "============================================="
    Write-Host "ZENrs GRUB2引导加载程序构建脚本"
    Write-Host "支持BIOS和UEFI双启动模式"
    Write-Host "============================================="
}

function Check-Prerequisites {
    Write-Host "检查必要的工具..."
    
    $required_tools = @("grub-mkimage", "grub-mkconfig", "xorriso", "gcc", "nasm")
    $missing_tools = @()
    
    foreach ($tool in $required_tools) {
        if (-not (Check-Command $tool)) {
            $missing_tools += $tool
        }
    }
    
    if ($missing_tools.Count -gt 0) {
        Write-Host "错误: 缺少以下必要工具: $($missing_tools -join ', ')"
        Write-Host "请在Linux环境下运行此脚本，或安装MinGW/MSYS2环境"
        exit 1
    }
    
    Write-Host "所有工具已就绪!"
}

function Create-Directories {
    Write-Host "创建目录结构..."
    New-Item -ItemType Directory -Force -Path $GRUB_DIR | Out-Null
    New-Item -ItemType Directory -Force -Path $EFI_DIR | Out-Null
    New-Item -ItemType Directory -Force -Path $CONFIG_DIR | Out-Null
    New-Item -ItemType Directory -Force -Path $OUTPUT_DIR | Out-Null
    Write-Host "目录创建完成!"
}

function Create-GrubConfig {
    Write-Host "创建GRUB配置文件..."
    
    # 主配置文件
    $grub_config = @"
# GRUB2配置文件 - ZENrs操作系统
# 支持BIOS和UEFI双启动模式

# 超时设置
set timeout=5
set default=0

# 背景设置（可选）
# set background_color=black
# set color_normal=light-gray/black
# set color_highlight=white/black

# 检测当前平台
if [ "${grub_platform}" = "efi" ]; then
    set platform="UEFI"
    # UEFI特定设置
    insmod efi_gop
    insmod efi_uga
else
    set platform="BIOS"
    # BIOS特定设置
    insmod vbe
    insmod vga
fi

# 显示欢迎信息
echo "ZENrs操作系统引导加载程序 (${platform}模式)"
echo "基于GRUB2构建，支持多系统引导"

# ZENrs菜单项
menuentry "ZENrs操作系统" {
    echo "正在加载ZENrs..."
    # TODO: 根据实际情况修改内核路径和参数
    insmod ext2
    set root=(hd0,1)
    multiboot /boot/exokernel.elf
    boot
}

# 高级选项子菜单
submenu "高级选项" {
    menuentry "ZENrs (调试模式)" {
        echo "正在加载ZENrs (调试模式)..."
        insmod ext2
        set root=(hd0,1)
        multiboot /boot/exokernel.elf debug=verbose
        boot
    }
    
    menuentry "ZENrs (单用户模式)" {
        echo "正在加载ZENrs (单用户模式)..."
        insmod ext2
        set root=(hd0,1)
        multiboot /boot/exokernel.elf single
        boot
    }
}

# 内存测试工具
menuentry "内存测试 (Memtest86+)" {
    echo "加载Memtest86+..."
    insmod memtest86+
    memtest86+
}

# 启动其他操作系统的示例
menuentry "从硬盘启动" {
    echo "从硬盘启动..."
    insmod chain
    set root=(hd0,1)
    chainloader +1
}
"@
    
    $grub_config | Out-File -FilePath "$GRUB_DIR/grub.cfg" -Encoding ASCII
    
    # 自定义配置脚本
    $custom_script = @"
#!/bin/sh
# 自定义GRUB菜单项脚本

cat << EOF
entry '启动UEFI Shell' {
    insmod chain
    chainloader /EFI/shellx64.efi
}

entry '重启计算机' {
    reboot
}

entry '关机' {
    halt
}
EOF
"@
    
    $custom_script | Out-File -FilePath "$CONFIG_DIR/40_custom" -Encoding ASCII
    
    # 设置执行权限
    chmod +x "$CONFIG_DIR/40_custom" 2>$null
    
    Write-Host "GRUB配置文件创建完成!"
}

function Create-Bootloader {
    Write-Host "构建BIOS引导加载程序..."
    # 创建BIOS版本的GRUB镜像
    grub-mkimage -o "$OUTPUT_DIR/boot.img" -p "(hd0,1)/boot/grub" -O i386-pc biosdisk part_msdos ext2
    
    Write-Host "构建UEFI引导加载程序..."
    # 创建UEFI版本的GRUB镜像
    grub-mkimage -o "$EFI_DIR/bootx64.efi" -p "(hd0,1)/boot/grub" -O x86_64-efi fat iso9660 part_gpt part_msdos
    
    Write-Host "引导加载程序构建完成!"
}

function Create-BootSector {
    Write-Host "创建主引导扇区..."
    # 创建MBR引导扇区
    dd if=/dev/zero of="$OUTPUT_DIR/mbr.bin" bs=512 count=1 2>$null
    grub-install --target=i386-pc --boot-directory="$BOOT_DIR" --no-floppy --force "$OUTPUT_DIR/mbr.bin" 2>$null
    
    Write-Host "主引导扇区创建完成!"
}

function Create-ISO {
    Write-Host "创建可启动ISO镜像..."
    $ISO_NAME = "zenrs-boot.iso"
    
    # 创建ISO镜像，同时支持BIOS和UEFI
    xorriso -as mkisofs -iso-level 3 -full-iso9660-filenames \
        -volid "ZENrs Boot" -eltorito-boot boot/grub/i386-pc/eltorito.img \
        -no-emul-boot -boot-load-size 4 -boot-info-table \
        -eltorito-alt-boot -e EFI/boot/bootx64.efi -no-emul-boot \
        -output "$OUTPUT_DIR/$ISO_NAME" "$BOOT_DIR" 2>$null
    
    Write-Host "ISO镜像创建完成: $OUTPUT_DIR/$ISO_NAME"
}

function Generate-Summary {
    Write-Host "============================================="
    Write-Host "构建完成! 已创建以下文件:"
    Write-Host "- GRUB配置文件: $GRUB_DIR/grub.cfg"
    Write-Host "- BIOS引导镜像: $OUTPUT_DIR/boot.img"
    Write-Host "- UEFI引导文件: $EFI_DIR/bootx64.efi"
    Write-Host "- 主引导扇区: $OUTPUT_DIR/mbr.bin"
    if (Test-Path "$OUTPUT_DIR/zenrs-boot.iso") {
        Write-Host "- 可启动ISO: $OUTPUT_DIR/zenrs-boot.iso"
    }
    Write-Host "============================================="
    Write-Host "使用说明:"
    Write-Host "1. 将boot目录复制到您的引导分区"
    Write-Host "2. 对于BIOS系统: 使用mbr.bin安装引导扇区"
    Write-Host "3. 对于UEFI系统: 确保EFI目录结构正确"
    Write-Host "4. 根据您的实际分区情况修改grub.cfg中的路径"
}

# 主函数
function Main {
    Print-Header
    Check-Prerequisites
    Create-Directories
    Create-GrubConfig
    
    # 尝试构建引导加载程序（在Windows下可能会失败）
    try {
        Create-Bootloader
        Create-BootSector
        Create-ISO
    } catch {
        Write-Host "警告: 在Windows环境下部分构建步骤可能失败，建议在Linux环境下运行完整构建"
        Write-Host "错误详情: $_"
    }
    
    Generate-Summary
}

# 执行主函数
Main